<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .talk_con {
            width: 600px;
            height: 700px;
            border: 1px solid blue;
            margin: 0px auto 0;
            background: #f9f9f9;
        }
        .talk_con p {
            font-size: 15px;
            color: blue;
        }
        .talk_con h1 {
            text-align: center;
        }
        .talk_show {
            width: 580px;
            height: 420px;
            border: 1px solid red;
            background: #fff;
            margin: 10px auto 0;
            overflow: auto;
        }
        .talk_input {
            width: 580px;
            margin: 10px auto 0;
        }
        .whotalk {
            width: 80px;
            height: 30px;
            float: left;
            outline: none;
        }
        .talk_word {
            width: 420px;
            padding: 0px;
            float: left;
            margin-left: 10px;
            outline: none;
            text-indent: 10px;
            border: 1px solid red;
        }
        .talk_sub {
            width: 56px;
            height: 30px;
            float: left;
            margin-left: 10px;
            background: red;
            border: none;
            color: #fff;
            border-radius: 20px;
            cursor: pointer;
        }
        .atalk {
            margin: 10px;
        }
        /*.atalk img {*/
        /*    width: 40px;*/
        /*    height: 40px;*/
        /*    border-radius: 50%;*/
        /*    float: left;*/
        /*}*/
        .atalk span {
            display: inline-block;
            background: #0181cc;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
            max-width: 200px;
            white-space: pre-wrap;
            text-align: left;
        }
        .btalk {
            margin: 10px;
            text-align: right;
        }
        .btalk img {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            float: right;
            margin-top: -10px;
        }
        .btalk span {
            display: inline-block;
            background: grey;
            border-radius: 10px;
            color: #fff;
            padding: 5px 10px;
            max-width: 200px;
            white-space: pre-wrap;
            text-align: left;
        }
        </style>
</head>
<body>
<div class="talk_con">
       <h1>欢迎进入聊天室</h1>
      <div class="talk_main">
          <div class="personnel-list">
              <ul class="personnel-list-ul">
                  测试1群
              </ul>
              <!-- 在线列表 -->
              <!-- 用户列表
          进入的时候拉取用户列表
          有人加入的时候添加
          有人退出以后删除 -->
          </div>
       <div class="talk_show" id="words">

           </div>
       <div class="talk_input">

            <!--select class="whotalk" id="who">

                 <option value="0">小哥哥说：</option>
                 <option value="1">小姐姐说：</option>
                </-->
            <textarea class="talk_word" id="talkwords"></textarea>
           <form id="form">
            <input type="submit" value="发送" class="msg" id="msg">
           </form>
           </div>
</div>
      </div>
</body>
</html>
<script src="http://91vh.com/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
    $(function() {
        var groups_id = 1        //群id
        function rand(minNum, maxNum) {
            return Math.floor(Math.random()*(minNum - maxNum) + maxNum);
        }
        function sendId() {
            let timeStamp = (new Date()).valueOf();
            let randId = rand(100000, 999999);
            let id = timeStamp + "-" + randId;
            return id
        }
        function getUrlParam(name)
        {
            var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r!=null) return unescape(r[2]); return null; //返回参数值
        }
        var conn;
        var msg = $("#talkwords");
        var log = $("#words");
        var uid=getUrlParam("uid");
        var to_uid=0
        groups_id=getUrlParam("groups_id");//群id
        if (groups_id==null){
            groups_id="1"
        }
        function appendLog(msg) {
            var d = log[0]
            var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
            msg.appendTo(log)
            if (doScroll) {
                d.scrollTop = d.scrollHeight - d.clientHeight;
            }
        }
        $("#form").submit(function() {
            if (!conn) {
                return false;
            }
            if (!msg.val()) {
                return false;
            }
            var json = {"seq": sendId(),"action":"sendmsg","data":{"userId":uid,"appId":1,"msgType":"text","toUid":"0","groupsId":groups_id,"message":msg.val()}}
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            conn.send(jsonStr);
            msg.val("");
            return false
        });

        if (window["WebSocket"]) {
            conn = new WebSocket("ws://localhost:8282/ws?uid="+uid+"&groups_id="+groups_id+"&appname=1");
            conn.onopen = function(evt) {
                console.log("Connection open ...");
                console.log("用户准备登陆:" + uid);
                conn.send('{"seq":"' + sendId() + '","action":"login","data":{"userId":"' + uid + '","appId":1,"toUid":"'+to_uid+'","groupsId":"'+groups_id+'"}}');

                // 定时心跳
                setInterval(heartbeat, 30 * 1000)
            };
            conn.onclose = function(evt) {
                appendLog($("<div><b>Connection Closed.</b></div>"))
            }
            conn.onmessage = function(evt) {
                console.log(evt.data)
                obj = JSON.parse(evt.data);
                if (obj.code !=undefined && obj.code!=200)
                {
                    appendLog($("<div/>").text("发送失败"))
                }else {

                    if (obj.data!=null && obj.data.action=="sendmsg")
                    {
                        data = obj.data
                        if (data.from ==uid)
                        {
                            appendLog($("<div/>").html('<div class="btalk"><span>' + data.content + '</span></div>'))
                        }else{
                            appendLog($("<div/>").html('<div class="atalk">用户'+data.from+'：<span>' + data.content + '</span></div>'))
                        }
                    }
                }
            }
            // 心跳
            function heartbeat() {
                // console.log("定时心跳:" + uid);
                conn.send('{"seq":"' + sendId() + '","action":"heartbeat","data":{}}');
            }
        } else {
            appendLog($("<div><b>WebSockets Not Support.</b></div>"))
        }
    });

</script>